package dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
public class 全排列2 {
    public static void main(String[] args) {
        int[] nums={1,1,2};
        List<List<Integer>> lists = permuteUnique(nums);
        System.out.println(lists.toString());
    }

    public static List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
        int len = nums.length;
        //标记是否访问过
        boolean[] m = new boolean[len];
        if (nums == null)
            return lists;
        Arrays.sort(nums);
        dfs(nums, len, 0, lists, list, m);
        return lists;
    }

    private static void dfs(int[] nums, int len, int depth, List<List<Integer>> lists, ArrayList<Integer> list, boolean[] m) {
        if (depth == len) {
            lists.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < len; i++) {
            //和前一个相等并且前一个（未被访问过），则跳过
            if (i>0 && nums[i]==nums[i-1] && !m[i-1])
                continue;
            if (!m[i]) {
                list.add(nums[i]);
                m[i] = true;
                System.out.println("递归之前     " + list);
                dfs(nums, len, depth + 1, lists, list, m);
                m[i] = false;
                list.remove(list.size() - 1);
                System.out.println("递归之后     " + list);
            }
        }
    }
}
